﻿#region [===== Using =====]
using System;
using System.Globalization;
using System.ComponentModel;
#endregion

namespace TPG.SharePoint.Workflow
{
  /// <summary>
  /// A special type of <see cref="WorkflowControlPlaceHolder" /> for 
  /// providing a placeholder for <see cref="WorkflowDataControl&lt;TData, TMetaData&gt;" /> controls.
  /// </summary>
  /// <typeparam name="TData">The <see cref="System.Type"/> of the 
  /// data class.</typeparam>
  /// <typeparam name="TMetaData">The <see cref="Type" /> of the
  /// metadata class.</typeparam>
  [ToolboxItem(false)]
  public class WorkflowDataControlPlaceHolder<TData, TMetaData>
      : WorkflowControlPlaceHolder
    where TData : class
    where TMetaData : WorkflowMetaData
  {
    #region [===== Public methods =====]
    /// <summary>
    /// Gets the <see cref="WorkflowDataControl&lt;TData, TMetaData&gt;" /> hosted in this 
    /// placeholder.
    /// </summary>
    /// <returns>The data control.</returns>
    public WorkflowDataControl<TData, TMetaData> GetWorkflowControl()
    {
      return (WorkflowDataControl<TData, TMetaData>)Control;
    }
    #endregion

    #region [===== Protected methods =====]
    /// <summary>
    /// Initializes the placeholder and verifies if the data control 
    /// provides the right type of data.
    /// </summary>
    /// <param name="e">An EventArgs containing event data.</param>
    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);

      IWorkflowDataPage<TData> page = Page as IWorkflowDataPage<TData>;
      if (page == null)
      {
        throw new WorkflowException(
            string.Format(CultureInfo.CurrentCulture, "This placeholder control must be placed on a page implementing IWorkflowDataPage<{0}>.",
                typeof(TData).AssemblyQualifiedName));
      }
      WorkflowDataControl<TData, TMetaData> control = Control as WorkflowDataControl<TData, TMetaData>;
      if (control == null)
      {
        throw new WorkflowException(
            string.Format(CultureInfo.CurrentCulture, "The placeholder control can only host controls deriving from WorkflowDataControl<{0}>.",
                typeof(TData).AssemblyQualifiedName));
      }

      SerializationMode? configuredMode = WorkflowConfiguration.GetSerializationMode(WorkflowPage.WorkflowTemplate, WorkflowPage.WorkflowMetaData.PageType);
      if (configuredMode != null)
      {
        control.SerializationMode = configuredMode.Value;
      }
    }
    #endregion
  }
}
